const {
  planPage,
  voluntaryTtem
} = require("../../../../api/api")
const {
  voluntaryAdd,
  voluntaryBatchAdd,
  planVoluntaryPage,
  special
} = require("../../../../api/ai")
const {
  returnLabel,
  throttle,
  filterObj
} = require("../../../../utils/util")

// pages/volunteer/components/planModal/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    majorIndex: {
      type: Number,
      value: 0
    },
    school: {
      type: Object,
      value: {}
    },
    visible: {
      type: Boolean,
      value: false
    },
    majorList: {
      type: Array,
      value: []
    },
    tempNo: {
      type: String,
      value: ''
    },
    useBatch: {
      type: String,
      value: '本科批'
    },
    mode: {
      type: String,
      value: 'batch'
    }

  },
  observers: {
    'visible': function (val) {
      if (val) {
        this.setData({
          tabIndex: 0,
          list: [],
          listData: [],
          moreList: [],
        })
      }
    },
    'school': async function (value) {
      if (value) {
        const lableList = returnLabel(value.school)
        this.setData({
          lableList,
          list: [],
          // listData: [],
          // moreList: [],
          pageNo: 1,
          status: true,
        })
      await this.voluntaryTtem(value)
        this.getSchoolData(value)
      }
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    yearList: ['2022','2021', '2020'],
    year: '2020',
    schoolPlanNum:0,
    matriculateNum:0,
    minObj:{},
    total: 0,
    listData: [],
    list: [],
    moreList: [],
    changeSort: '',
    tabIndex: 0,
    pageSize: 999,
    pageSizeT: 10,
    pageNo: 1,
    major: {},
    isChecked: true,
    bottomLift: getApp().globalData.bottomLift,
    currentList: [],
    originTotal: 0,
    rangeVisible: false,
    changeItem: null,
    status: true,
    selectIndex:null
  },

  /**
   * 组件的方法列表
   */
  methods: {
    changeIndex(e) {
      const {
        school,
        year,
        tabIndex
      } = this.data
      const {
        index,
        type
      } = e.currentTarget.dataset
      if (index == this.data[type]) return
      // index ? school.year = year : 2022
      this.setData({
        [type]: parseInt(index),
        // school,
        // list: [],
        // specialList:[],
        // pageNo: 1,
      })
      // if(!index)return
      // this.getOldSpecial()
    },
    syncData(index) {

    },
    queryShow(e){
      const {index}=e.currentTarget.dataset
      const {
        selectIndex
      } = this.data
      this.setData({
        selectIndex:selectIndex || selectIndex==0 || (!index && index!=0)?null:index
      })
    },
    looKchange(e){
      const {
        index,
        type
      } = e.currentTarget.dataset
      const list=this.data[type]
      list[index].show=true
      this.setData({
        [type]:list
      })
    },
    getList() {
      let {
        listData,
        moreList,
      } = this.data
      if(listData.length<=0){
        let schoolPlanNum=0
        moreList.map((item) => {
          schoolPlanNum+=item.num
        })
        this.setData({
          schoolPlanNum,
        })
      }
      this.setData({
        list: [...listData, ...moreList],
      })
    },
    checkItem(e) {
      const {
        type,
        checked
      } = e.currentTarget.dataset
      this.setData({
        [type]: !checked
      })
    },
    //填报
    // toggle:throttle (async function(e) {
    async toggle(e) {
      const {
        currentList,
        list,
        majorList,
        majorIndex,
        mode
      } = this.data
      const major = majorList[majorIndex]
      if (mode == 'single') {
        //平行志愿
        const {
          data,
          checked,
          index,
          sort
        } = e.currentTarget.dataset
        const {
          majorList,
          list,
          tempNo,
          school,
          pageNo
        } = this.data

        let params = {
          localBatchName: data.localBatchName,
          planId: data.id,
          schoolSgId:data.schoolSgId,
          schoolId: data.schoolId,
          schoolName: data.schoolName,
          schoolSpecialtyId: data.speId,
          specialtyCode: data.spcode,
          specialtyName: data.sptitle,
          matchRate: data.matchRate,
          tempId: tempNo,
          active: data.matchEn,
        }
        if (sort) {
          params.sort = sort
          params.speSort = sort

        } else {
          const newList = majorList.filter((item) => {
            return item.checked == false
          })
          params.sort = newList[0].sort
          params.speSort = newList[0].sort
        }
        const result = await voluntaryAdd(params)
        await this.getSchoolData(school)
        // await this.getMoreSpecial()
        // this.getList()
        await this.triggerEvent('load', {
          changeSort: params.speSort,
          newSort: null,
          planId: data.id,
          chooseType: 'single',
        })

      } else {
        const {
          data,
          checked,
          index
        } = e.currentTarget.dataset
        list[index].checked = !checked
        if (checked) {
          list[index].selectSpeSort = ''
          currentList.map((item, index) => {
            if (item.planId == data.id) {
              currentList.splice(index, 1)
            }
          })
        } else {
          if (currentList.length >= major.specialNum) {
            list[index].checked = false
            wx.showToast({
              title: '当前专业组只能填报' + major.specialNum + '专业',
              icon: 'none'
            })
            return
          }
          const numAry = []
          for (let i = 1; i < major.specialNum + 1; i++) {
            numAry.push(i)
          }
          const selectList = []
          currentList.map(e => {
            selectList.push(String(e.selectSpeSort))
          })
          let numList = []
          numList = numAry.filter(item => {
            return selectList.indexOf(String(item)) === -1
          });
          let min = Math.min.apply(Math, numList.map(e => {
            return e
          }))
          data.selectSpeSort = String(min)
          list[index].selectSpeSort = String(min)
          data.planId = data.id
          currentList.push(data)
        }
        this.setData({
          list,
          currentList,
          selectIndex:null
        })
      }
    },
    promiseConfirm() {
      const {
        changeItem,
        changeSort
      } = this.data
      return new Promise((resolve, reject) => {
        if (changeSort) {
          wx.showModal({
            title: '提示',
            content: changeItem.name + '已经存在,是否替换',
            success: async function (res) {
              if (res.confirm) {
                resolve(true)
              } else {
                resolve(false)
              }
            },
          })
        } else {
          resolve(true)
        }

      })
    },
    promiseCancel() {
      const {
        changeItem,
        currentList,
        originTotal,
        majorList,
        majorIndex,
        originIndex
      } = this.data
      const name = majorList[majorIndex].name
      var _this = this
      return new Promise((resolve, reject) => {
        if (changeItem) {
          wx.showModal({
            title: '提示',
            content: changeItem.name + '已经修改,是否保存',
            success: async function (res) {
              if (res.confirm) {
                resolve(true)
              } else {
                _this.setData({
                  majorIndex: originIndex,
                })
                resolve(false)
              }
            },
          })
        } else {
          if (currentList.length !== originTotal) {
            wx.showModal({
              title: '提示',
              content: name + '已修改，是否保存',
              success(res) {
                if (res.confirm) {
                  resolve(true)
                } else {
                  resolve(false)
                }
              },
            })
          } else {
            resolve(false)
          }

        }

      })
    },
    async addSingleVoluntary() {

    },
    // 保存志愿表
    async confirmVolunteer(e) {
      const flag = await this.promiseConfirm()
      if (flag) {
        this.addVolunteer()
      } else {
        this.setData({
          visible: false,
          originTotal: 0,
          currentList: [],
          changeItem: null,
          originIndex: null
        })
      }
    },
    async addVolunteer(e) {
      const {
        tempNo,
        majorList,
        majorIndex,
        school,
        list,
        changeSort,
        newSort,
        currentList,
        changeItem,
        isChecked
      } = this.data
      const major = majorList[majorIndex]
      console.log()
      const selectList = currentList.map((item, index) => {
        return {
          localBatchName: item.localBatchName,
          planId: item.planId,
          schoolId: item.schoolId,
          schoolSgId:item.schoolSgId,
          schoolName: item.schoolName,
          schoolSgName: item.schoolSgName,
          matchRate: item.matchRate,
          schoolSpecialtyId: item.speId,
          specialtyCode: item.spcode,
          specialtyName: item.sptitle,
          sort: major.sort,
          speSort: item.selectSpeSort,
          tempId: tempNo,
          active: item.matchEn,
        }
      })
      const params = {
        list: selectList,
        tempId: tempNo,
        isChecked
      }
      if (changeSort) {
        params.changeSort = changeSort
        params.newSort = newSort
      }
      var result = await voluntaryBatchAdd(params)
      if (result.success) {
        this.triggerEvent('load', {
          changeSort: changeSort ? changeSort : major.sort,
          newSort: changeSort ? newSort : null
        })
        this.setData({
          visible: false,
          currentList: [],
          originTotal: 0,
          changeSort: null,
          changeItem: null
        })
        wx.showToast({
          title: result.message,
          icon: 'none'
        })
      }
    },
    bindPickerChange(e) {
      const index = parseInt(e.detail.value)
      this.setData({
        majorIndex: index,
      })
    },
    yearTab(e) {
      const {
        year
      } = e.currentTarget.dataset
      const {
        school
      } = this.data
      school.year = year
      this.setData({
        year,
        // list: [],
        // pageNo: 1,
        // school
      })
      // this.getOldSpecial()
      this.getHistoryTotal()
    },
    //查看该专业组更多专业推荐
    async getMoreSpecial() {
      var {
        pageNo,
        tabIndex,
        year,
        list,
        tempNo,
        pageSizeT,
        majorList,
        school,
        total,
        majorIndex,
        originTotal,
        currentList,
      } = this.data
      if (pageNo != 1 && total <= pageNo * pageSizeT) return
      const params = {
        pageSize: pageSizeT,
        pageNo,
        schoolId: school.school.id,
        schoolName: school.school.name,
        provinceId: school.provinceId,
        year: !tabIndex ? 2022 : year,
        voluntaryTempId: majorList[majorIndex].voluntaryTempId,
        localBatchName: this.data.useBatch,
        active: school.active,
        showMore: true,
      }
      const {
        result
      } = await planVoluntaryPage(params)
      console.log(result)
      result.records.map((item) => {
        item.selectSort ? item.checked = true : item.checked = false
      })
      this.setData({
        moreList: result.records,
        total: result.total,
        status: false,
        // pageNo:pageNo+1
      })
      this.getList()
    },
    // 获取历史录取
    async getOldSpecial() {
      var {
        tabIndex,
        year,
        majorList,
        school,
        majorIndex,
        listData,
        moreList
      } = this.data
      const params = {
        schoolId: school.school.id,
        schoolName: school.schoolName,
        provinceId: school.provinceId,
        year:year,
        voluntaryTempId: majorList[majorIndex].voluntaryTempId,
        localBatchName: this.data.useBatch,
        active: school.active,
        showMore: true,
        type:school.params.firstSelect?school.params.firstSelect+'类':''
      }
      const {
        result
      } = await special(params)
      let arr=this.data.list.map(e=>{return e.sptitle})
      // if(listData.length<=0){
      //   arr=moreList.map(e=>{return e.sptitle})
      // }else{
      //   arr=listData.map(e=>{return e.sptitle})
      // }
      let matriculateNum=0
      // const specialList=result.filter(e=>{
      //   if(arr.indexOf(e.sptitle)>-1){
      //     matriculateNum+=e.num
      //       return e
      //   }
      // })
      const specialList=result
     let newArr=specialList.sort((a,b)=>{
        return a.min-b.min
      })
    //   let min = Math.min.apply(Math,specialList.map(e => {
    //      return e.min 
    //   }))
    //   let minSection = Math.min.apply(Math,specialList.map(e => {
    //     return e.minSection
    //  }))
      this.setData({
        specialList,
        minObj:newArr.length>0?newArr[0]:{},
        matriculateNum,
        status: false,
      })
    },
    
    // loadMore() {
    //   const {
    //     total,
    //     list,
    //     school,
    //   } = this.data
    //   if (list.length < total) {
    //     this.getSchoolData(school)
    //   }
    // },
    // 获取已选专业
    async voluntaryTtem(value) {
      var {
        school,
        tempNo,
        tabIndex
      } = this.data
      const params = {
        tempId: tempNo,
        schoolId: school.school.id
      }
      if(tabIndex)return
      const {
        result
      } = await voluntaryTtem(params)
      result.map(e => {
        e.selectSpeSort = e.speSort
        e.sptitle = e.specialtyName
        e.spcode = e.specialtyCode
        e.speId = e.schoolSpecialtyId
        e.matchEn = e.active
      })
      this.setData({
        currentList: result,
        originTotal: result.length
      })
    },
    // 获取全部专业数据
    // async getAllSchoolData(value){
    //   var {
    //     pageNo,
    //     tabIndex,
    //     year,
    //     list,
    //     tempNo,
    //     majorList,
    //     majorIndex,
    //     originTotal,
    //     currentList
    //   } = this.data
    //   const params = {
    //     pageSize:9999,
    //     pageNo,
    //     schoolId: value.school.id,
    //     provinceId: value.provinceId,
    //     year: !tabIndex ? 2022 : year,
    //     voluntaryTempId: majorList[majorIndex].voluntaryTempId,
    //     localBatchName: this.data.useBatch,
    //     active:'all'
    //   }
    //   const {
    //     result
    //   } = await planVoluntaryPage(params)
    //   let array=result.records
    //   params.showMore=true
    //   const res = await planVoluntaryPage(params)
    //   array=[...array, ...res.result.records]
    //   array.map((item) => {
    //     if (item.selectSort) {
    //       // item.matchRate=(item.matchRate*100).toFixed(1)
    //       currentList.push(item)
    //       originTotal += 1
    //     }
    //   })
    //   console.log(currentList)
    //   this.setData({
    //     currentList
    //   })
    // },
    async getSchoolData(value) {
    
      var {
        pageSize,
        pageNo,
        tabIndex,
        year,
        list,
        tempNo,
        majorList,
        majorIndex,
        // originTotal,
        currentList
      } = this.data
      if(tabIndex)return
      let obj={}
      if (value.params) {
           obj={
            specialtyIds:value.params.specialtyIds,
            schoolTypeList:value.params.schoolTypeList,
            schoolProvinceId:value.params.schoolProvinceId,
            eduType:value.params.eduType,
            eduLevelName:value.params.eduLevelName,
            schoolType:value.params.schoolType,
          }
      }
      let params = {
        pageSize,
        pageNo,
        schoolId: value.school.id,
        provinceId: value.provinceId,
        startScore: value.params.startScore,
        endScore: value.params.endScore,
        schoolName: value.params.schoolName,
        schoolSgId: value.schoolPlan.schoolSgId,
        year: !tabIndex ? 2022 : year,
        voluntaryTempId: majorList[majorIndex].voluntaryTempId,
        localBatchName: this.data.useBatch,
        active: value.active
      }
      params = filterObj(Object.assign(obj, params))
      const {
        result
      } = await planVoluntaryPage(params)
      let   yearList= Object.keys(result[0].historyMap).map(e=>{
          return  e
        })
        yearList.sort((a,b)=>{
          return b-a
        })
      // let matriculateNum=0
      result.map((item) => {
        // item.matchRate=(item.matchRate*100).toFixed(1)
        item.selectSort ? item.checked = true : item.checked = false
        // if (item.selectSort) {
        // currentList.push(item)
        // originTotal += 1
        // }
      })
      // const param=params
      // param.active='all'
      // param.pageSize='9999'
      // const res = await planVoluntaryPage(param)
      // res.result.records.map((item) => {
      //   if (item.selectSort) {
      //     // item.matchRate=(item.matchRate*100).toFixed(1)
      //     currentList.push(item)
      //     originTotal += 1
      //   }
      // })
      // if (!result.total) {
      //   this.getMoreSpecial()
      // }
      let schoolPlanNum=0
      result.map(e=>{
        schoolPlanNum+=e.num
      })
      this.setData({
        list:result,
        yearList,
        schoolPlanNum,
        year:yearList[0]
      })
      this.getHistoryTotal()
    },
    // 历史录取总人数 最低分排名
    getHistoryTotal(){
      const {list,year}=this.data
     let matriculateNum=0
     const newArr=[]
      list.map((item) => {
        matriculateNum+=item.historyMap[year].num
        newArr.push(item.historyMap[year])
      })
      newArr.sort((a,b)=>{
        return a.min-b.min
      })
      let minObj=newArr.filter(e=>{return e.min})[0]
      this.setData({
        matriculateNum,minObj
      })
    },
    async hide() {
      const flag = await this.promiseCancel()
      //flag为true, 则保存
      if (flag) {
        this.addVolunteer()
      }
      this.setData({
        visible: false,
        originTotal: 0,
        currentList: [],
        changeItem: null,
        originIndex: null,
        changeSort: null,
      })
    },
    rangeChange(e) {
      const index = e.detail.current
      var range = e.detail.range
      this.setData({
        majorIndex: index,
        majorList: range,
      })
    },
    changeDesc(e) {
      const index = e.detail.current
      const value = e.detail.value //原来的item
      var range = e.detail.range
      var type = e.detail.type
      const changeItem = range[index]
      this.setData({
        majorIndex: index,
        majorList: range,
        changeItem: changeItem,
        originIndex: value,
        changeSort: type == 'origin' ? null : value + 1,
        newSort: index + 1
      })
    },
    openPicker() {
      const {
        majorList
      } = this.data

      this.setData({
        rangeVisible: true
      })
    },
    confirm() {
      const {
        majorIndex,
        majorList
      } = this.data
      this.triggerEvent('update', {
        majorIndex,
        majorList
      })
    },
    goto(e) {
      const {
        url
      } = e.currentTarget.dataset
      wx.navigateTo({
        url: url,
      })
    },
    clear() {
      const {
        list
      } = this.data
      list.map(e => {
        e.selectSpeSort = ''
        e.checked = false
      })
      this.setData({
        currentList: [],
        list
      })
    }
  }
})